import {  Component, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { SimpleOrganinzationUnitDto, UserOrganinzedCacheItem, UserRoleUnitSelectionServiceProxy, WorkFlowDesignServiceProxy, WorkFlowSelectUnitsDto } from '@shared/service-proxies/service-proxies';
import { ArrayToTreeConverterService } from '@shared/utils/service/array-to-tree-converter.service';
import { TreeDataHelperService } from '@shared/utils/service/tree-data-helper.service';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { TreeNode } from 'primeng/api';
import { UserHelper } from '../user-helper.service';
import { ISelectionUserBackData } from '../workflow-common-interface';



@Component({
    selector: 'selection-user-box',
    templateUrl: './selection-user-box.component.html'
})
export class SelectionUserBoxModalComponent extends AppComponentBase {
    @ViewChild('selectionModal', { static: true }) modal: ModalDirective;
    @Output() selectUserModalSave: EventEmitter<ISelectionUserBackData> = new EventEmitter<ISelectionUserBackData>();

    treeData: TreeNode<SimpleOrganinzationUnitDto>[];
    selectedTreeData: TreeNode<SimpleOrganinzationUnitDto>[] = [];
    userIds:number[] = [];
    workflowId:string = '';

    selectUsers:UserOrganinzedCacheItem[] = [];
    showUsers:UserOrganinzedCacheItem[] = []; 
    allUsers:UserOrganinzedCacheItem[] = [];
    searchModel = '';
    constructor(
        injector: Injector,
        private _arrayToTreeConverterService: ArrayToTreeConverterService,
        private _treeDataHelperService: TreeDataHelperService,
        private _userRoleUnitSelectionServiceProxy:UserRoleUnitSelectionServiceProxy,
        private _workFlowDesignServiceProxy:WorkFlowDesignServiceProxy,
        private _userHelper:UserHelper
    ) {
        super(injector);
    }

    show(userIds:string,workflowId:string): void {
        if (userIds){
            this.userIds = userIds.split(',').map(item=>Number(item));
        }
        else this.userIds = [];
        this.workflowId = workflowId;
        this.selectUsers = [];
        this.showUsers = []; 
        this.allUsers = [];
        this.searchModel = '';
        this.modal.show();

        this.initData();
    }

    searchUser(){
        let showUsers = [];
        if (!this.searchModel) {
            return;
        }

        let uids:number[] = [];
        this.allUsers.filter(item=>{
            if(item.displayName.indexOf(this.searchModel) > -1 && uids.indexOf(item.id) < 0){
                uids.push(item.id);
                showUsers.push(item);
            }
        })
        this._userHelper.userSort(showUsers);
        this.showUsers = showUsers;
    }

    setTreeData(permissions: SimpleOrganinzationUnitDto[]) {
        this.treeData = this._arrayToTreeConverterService.createTree(permissions, 'parentId', 'id', null, 'children',
            [{
                target: 'label',
                source: 'displayName'
            }, {
                target: 'expandedIcon',
                value: 'fa fa-folder-open text-warning'
            },
            {
                target: 'collapsedIcon',
                value: 'fa fa-folder text-warning'
            },
            {
                target: 'expanded',
                value: false
            }]);
    }
    
    save(): void {
        let ids = this.selectUsers.map(item=>item.id).join(',');
        let names = this.selectUsers.map(item=>item.displayName).join(',');

        this.selectUserModalSave.emit({
            ids:ids,
            names:names,
        });
        this.close();
    }

    getSelectionData(user:UserOrganinzedCacheItem){
        if (this.selectUsers.indexOf(user) < 0){
            this.selectUsers.push(user);
        }
        this._userHelper.userSort(this.selectUsers);
    }

    removeSelectUser(user:UserOrganinzedCacheItem){
        let index = this.selectUsers.indexOf(user);
        if (index > -1) {
            this.selectUsers.splice(index, 1);
        }
    }

    nodeSelect(e){
        let unitIds = this.selectedTreeData.map(item=>item.data.id);
        this.getShowUserByUnitIds(unitIds);
    }

    onNodeUnselect(e){
        let unitIds = this.selectedTreeData.map(item=>item.data.id);
        this.getShowUserByUnitIds(unitIds);
    }

    openAll(){
        this._treeDataHelperService.operateTreeNode(this.treeData,(item)=>{
            item.expanded = true;
        })
    }

    closeAll(){
        this._treeDataHelperService.operateTreeNode(this.treeData,(item)=>{
            item.expanded = false;
        })
    }

    clearAllData(){
        this.selectUsers = [];
    }

    addAllShowUser(){
        if (this.showUsers.length == 0) {
            return;
        }

        this.showUsers.forEach(item=>{
            this.getSelectionData(item);
        });
    }

    close(): void {
        this.modal.hide();
    }

    private initData(){
        this._workFlowDesignServiceProxy.getFilterUnits(this.workflowId).subscribe(res=>{
            this.setTreeData(res.unitList);
        })

        this.getUserData();
    }


    private getUserData(){
        this._userRoleUnitSelectionServiceProxy.getUserOrganinzation().subscribe(res=>{
            this.allUsers = res; 
            let uids:number[] = [];  
            for (const item of res) {
                 if (this.userIds.indexOf(item.id) > -1 && uids.indexOf(item.id) < 0){
                    this.selectUsers.push(item);
                    uids.push(item.id);
                 }
             }
        });
    }

    private getShowUserByUnitIds(unitIds:number[]){
        let showUsers = [];
        let uids:number[] = [];
        this.allUsers.forEach(item=>{
            if (uids.indexOf(item.id) > -1) return;
            if (unitIds.indexOf(item.organizationId) > -1){
                uids.push(item.id);
                showUsers.push(item);
            }
        })
        this._userHelper.userSort(showUsers);
        this.showUsers = showUsers;
    }
   
}
